package service

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto/rpc"
	"api-gateway/handler/request"
	"api-gateway/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	result, _ := config.Rdb.Get(config.Ctx, "smsCode_"+form.Phone).Result()
	if result != form.SmsCode {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "验证码错误"})
		return
	}
	user, err := config.UserRpcClient.Register(c, &__.RegisterReq{
		Phone:    form.Phone,
		SmsCode:  form.SmsCode,
		Password: pkg.Md5(form.Password),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "注册成功", "data": gin.H{
		"user": user.UserId,
	}})
	return
}
func Login(c *gin.Context) {
	var form request.Login
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	user, err := config.UserRpcClient.Login(c, &__.LoginReq{
		Phone:    form.Phone,
		Password: pkg.Md5(form.Password),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	token, err := pkg.GetJwtToken(int(user.UserId))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "登录成功", "data": gin.H{
		"user":  user.UserId,
		"token": token,
	}})
	return
}

func GetUserInfoById(c *gin.Context) {
	userId := c.GetFloat64("userId")
	user, err := config.UserRpcClient.GetUserInfo(c, &__.GetUserInfoReq{
		UserId: int64(userId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "登录成功", "data": gin.H{
		"phone":     user.Phone,
		"nickName":  user.NickName,
		"avatarUrl": user.AvatarUrl,
	}})
	return
}
